package org.kotboot.intercepter

import com.alibaba.fastjson.JSON
import com.alibaba.fastjson.JSONObject
import io.jsonwebtoken.*
import org.kotboot.annotations.Auth
import org.kotboot.cons.ConsJwt
import org.kotboot.exception.AuthFailedException
import org.kotboot.kit.Kit
import org.kotboot.kit.isNull
import org.kotboot.service.SignServ
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.context.annotation.Configuration
import org.springframework.stereotype.Component
import org.springframework.web.method.HandlerMethod
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse


@Component
open class AuthIntercepter (
): HandlerInterceptorAdapter(){
    val LOG : Logger = LoggerFactory.getLogger(AuthIntercepter::class.java)

    @Autowired val consJwt:ConsJwt?=null

    override fun preHandle(request: HttpServletRequest, response: HttpServletResponse, handler: Any): Boolean {
        if(handler is HandlerMethod){
            val methodAnnotation = handler.getMethodAnnotation(Auth::class.java)
            var needAuth:Boolean = true
            val classAuth = handler.beanType.getAnnotation(Auth::class.java)
            LOG.info("methodAnnotation:{},classAnnotation:{}",methodAnnotation,classAuth)
            if(isNull(methodAnnotation) && isNull(classAuth)){
                needAuth = false
            }
            if(needAuth){
                authCheck(request,response)
            }
            LOG.info("authCheck Over:{}",request.method)
        }
        return super.preHandle(request, response, handler)
    }

    fun authCheck(request: HttpServletRequest,response: HttpServletResponse){
        LOG.info("authCheck:{}",request.requestURI)
        val jwtcode: String = request.getHeader("x-session")
        if(Kit.notJwtcode(jwtcode)){
            throw AuthFailedException("身份校验失败")
        }
        lateinit var parse: Jws<Claims>
        try{
            parse = consJwt!!.parse(jwtcode)
        }catch (ex:ExpiredJwtException) {
            throw  AuthFailedException("登录超时，请重新登录")
        }catch (ex : Exception){
            LOG.info("身份校验失败：异常是：{}",ex.javaClass.name)
            throw AuthFailedException("身份校验失败")
        }
        //TODO 使用Bean来保存会员信息
        val userInfo: JSONObject = JSON.parseObject(parse.body.subject)
        request.setAttribute("userid",userInfo["userid"])
        request.setAttribute("userInfo",userInfo)
    }
}